package com.roy.galaxy.service;
import com.roy.galaxy.constant.RedisConstant;
import com.roy.galaxy.algorithm.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by mc on 18/4/10.
 */
@Service
public class IdGeneratorServiceImpl implements IdGeneratorService {

    @Autowired
    private  RedisService redisService;

    @Override
    public Long generatorId(Integer bizId, Long maxId) {
        try {
            String s = bizId.toString();
            Object object = redisService.get(redisService.getRedisKey());
            if(object == null){
                redisService.set(redisService.getRedisKey(),maxId.toString());
                String maxString = maxId.toString();
                return Long.parseLong(s + maxString);
            }else {
                Object objectIncr =redisService.decrease(redisService.getRedisKey());
                String objectString =  objectIncr.toString();
                return Long.parseLong(s + objectString);
            }
        } catch (Exception e) {
            LogUtil.getDefaultLog().error("IdGeneratorService#generatorId,error:{}", e.getMessage());
            return null;
        }
    }

    @Override
    public Long generatorId(Integer bizId) {
        try {
            String s = bizId.toString();
            Object object = redisService.get(redisService.getRedisKey());
            if(object == null){
                redisService.set(redisService.getRedisKey(),RedisConstant.START.toString());
                return Long.parseLong(s + RedisConstant.START);
            }else {
                redisService.decrease(redisService.getRedisKey());
                Object objectIncr = redisService.get(redisService.getRedisKey());
                String objectString =  objectIncr.toString();
                return Long.parseLong(s + objectString);
            }
        } catch (Exception e) {
            LogUtil.getDefaultLog().error("IdGeneratorService#generatorId,error:{}", e.getMessage());
            return null;
        }
    }
}
